package com.jzy.secondhandbooktradingmanagement.controller;

import com.jzy.secondhandbooktradingmanagement.LoginUser;
import com.jzy.secondhandbooktradingmanagement.commom.Result;
import com.jzy.secondhandbooktradingmanagement.service.IBookService;
import com.jzy.secondhandbooktradingmanagement.service.ITradeOrderService;
import com.jzy.secondhandbooktradingmanagement.service.IUserService;
import com.jzy.secondhandbooktradingmanagement.utils.IRedisUtil;

import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/dashboard")
public class DashboardController {
    @Resource
    private IUserService userService;
    @Resource
    private ITradeOrderService tradeOrderService;
    @Resource
    private IBookService bookService;
    @Resource
    private IRedisUtil redisUtil;

    @GetMapping
    public  Result<?> dashboardrecords(){
        // 尝试从缓存获取
        String cacheKey = "dashboard:records";
        Map<String, Object> cachedMap = redisUtil.getValue(cacheKey);
        if (cachedMap != null) {
            return Result.success(cachedMap);
        }

        int visitCount = LoginUser.getVisitCount();
        long userCount = userService.count();
        long orderCount = tradeOrderService.count();
        long bookCount = bookService.count();
        Map<String, Object> map = new HashMap<>();//键值对形式
        map.put("visitCount", visitCount);//放置visitCount到map中
        map.put("userCount", userCount);
        map.put("orderCount", orderCount);
        map.put("bookCount", bookCount);

        // 存入缓存，设置过期时间，例如 10 分钟
        redisUtil.setValue(cacheKey, map, 10 * 60 * 1000L);

        return Result.success(map);
    }
}
